package io.persimmon.core.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
public class FileTypeUtil {
    public static String fileType(String filePath) {
        try (FileInputStream fis = new FileInputStream(new File(filePath))) {
            byte[] header = new byte[12]; // 读取12字节可覆盖常见文件头

            if (fis.read(header) != header.length) {
                return "UNKNOWN";
            }

            // 按格式特征顺序检测
            if (isWav(header)) return "WAV";
            if (isMp3(header)) return "MP3";
            if (isPng(header)) return "PNG";
            if (isJpeg(header)) return "JPEG";
            if (isGif(header)) return "GIF";
            if (isBmp(header)) return "BMP";
            if (isZip(header)) return "ZIP";   // 新增ZIP格式检测
            if (isPdf(header)) return "PDF";   // 新增PDF格式检测

            return "UNKNOWN";
        } catch (IOException e) {
            log.error("File format detection failed", e);
            return "UNKNOWN";
        }
    }

    // 各格式检测封装成独立方法
    private static boolean isWav(byte[] header) {
        return header[0] == 'R' && header[1] == 'I' && header[2] == 'F' && header[3] == 'F'
                && header[8] == 'W' && header[9] == 'A' && header[10] == 'V' && header[11] == 'E';
    }

    private static boolean isMp3(byte[] header) {
        return (header[0] == 'I' && header[1] == 'D' && header[2] == '3') || // ID3
                ((header[0] & 0xFF) == 0xFF && (header[1] & 0xE0) == 0xE0);   // MPEG
    }

    private static boolean isPng(byte[] header) {
        return header[0] == (byte) 0x89 && header[1] == 'P' &&
                header[2] == 'N' && header[3] == 'G' &&
                header[4] == '\r' && header[5] == '\n' &&
                header[6] == 0x1A && header[7] == '\n';
    }

    private static boolean isJpeg(byte[] header) {
        return (header[0] & 0xFF) == 0xFF &&
                (header[1] & 0xFF) == 0xD8 &&
                (header[2] & 0xFF) == 0xFF;
    }

    private static boolean isGif(byte[] header) {
        return header[0] == 'G' && header[1] == 'I' &&
                header[2] == 'F' && header[3] == '8';
    }

    private static boolean isBmp(byte[] header) {
        return header[0] == 'B' && header[1] == 'M';
    }

    // 新增格式检测方法
    private static boolean isZip(byte[] header) {
        return header[0] == 0x50 && header[1] == 0x4B &&
                header[2] == 0x03 && header[3] == 0x04;
    }

    private static boolean isPdf(byte[] header) {
        return header[0] == '%' && header[1] == 'P' &&
                header[2] == 'D' && header[3] == 'F';
    }

}
